import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:stock_check/common/db/SqliteManage.dart';
import 'package:stock_check/common/db/TaskModel.dart';
import 'package:stock_check/common/http/Api.dart';
import 'package:stock_check/common/http/HttpManager.dart';
import 'package:stock_check/common/model/TaskDetail.dart';
import 'package:stock_check/common/model/taskItem.dart';
import 'package:stock_check/common/model/taskItemDetail.dart';
import 'package:stock_check/common/model/uploadTaskBean.dart';

class TasksDao{
  static final formatter = new DateFormat('yyyy-MM-dd');

  // 上传数据
  static Future<bool> uploadTaskData(int id, List<UploadTaskBean> list) async{
    var res;
    try{
      Dio dio = new Dio(Options(
          baseUrl: Api.baseUrl
      ));
      TaskDetail taskDetail = new TaskDetail();
      taskDetail.inventoryBy = id;
      taskDetail.taskList = list;
      Map<String,dynamic> map = {
        "taskDetail":TaskDetail.toJson(taskDetail)
      };
      FormData formData = new FormData.from({
        "taskResult":json.encode(map)
      });
      res = await dio.post(Api.uploadTasks,data:formData);
      return json.decode(res.data)['result'];
    }catch(e){
      Fluttertoast.showToast(msg:e.toString());
      return false;
    }
  }

  // 根据记录ID获取所有盘点任务
  static Future<List<TaskDetailItem>> findTaskListByTaskID(int taskId)async{
    List<TaskDetailItem> tasks =  await getTaskDetailList(formatter.format(DateTime.now()));
    List<TaskDetailItem> list = new List();
    if(tasks.isNotEmpty){
      for(int i=0;i<tasks.length;i++){
        if(tasks[i].taskId == taskId){
          list.add(tasks[i]);
        }
      }
      return list;
    }
    return null;
  }

  static getCurrentTime(){
    return formatter.format(DateTime.now());
  }

  /// 更新盘点id更新数据
  static Future<List<TaskDetailItem>> updateTaskListByID(TaskDetailItem item) async{
    List<TaskDetailItem> tasks = await getTaskDetailList(getCurrentTime());
    DataBase dataBase = new DataBase();
    TaskModel taskModel = new TaskModel();
    taskModel.updateTime = getCurrentTime();
    bool flag = false;
    if(tasks.isNotEmpty){
      for(int i=0;i<tasks.length;i++){
        if((tasks[i].taskId == item.taskId) && (tasks[i].eqptNo == item.eqptNo)){
          tasks[i] = item;
          flag = true;
          break;
        }
      }
    }
    if(!flag) Fluttertoast.showToast(msg: '更新失败!');
    else{
      taskModel.jsonTxt = json.encode(tasks);
      await dataBase.updateTaskModel(taskModel);
      Fluttertoast.showToast(msg: '更新成功!');
    };
    return tasks;
  }

  // 获取盘点列表
  static Future<List<TaskItem>> getTasksList(int deptId,String updateTime) async{
    DataResult res = await HttpManager.netFetch(Api.inventoryTasks, {'deptId':deptId});
    if(res.data!=null&&res.result!=false){
      List<TaskDetailItem> tasks = await getTaskDetailList(updateTime);
      List<TaskItem> list = new List();
      if(res.data!=null&&res.result!=false){
        var jsonList = json.decode(res.data);
        var arr = jsonList['resultData'];
        for(int i=0;i<arr.length;i++){
          TaskItem item = TaskItem.fromJson(arr[i]);
          item.ifDownloadStr = '未下载';
          if(tasks!=null&&_checkDownLoad(tasks,item)){
            item.ifDownloadStr = '已下载';
          }
          item.check = false;
          list.add(item);
        }
        return list;
      }
    }else{
      throw Exception('error');
    }
  }

  // 下载盘点数据
  static Future<List<TaskDetailItem>> downLoad(List<TaskItem> items,String ids) async{
    try{
      DataResult res = await HttpManager.netFetch(Api.downloadTasks, {"taskIds":ids});
      var jsonTxt = json.decode(res.data);
      List<TaskDetailItem> tasks = new List();
      List list = jsonTxt['resultData'];
      if(list.length>0){
        for(int i=0;i<list.length;i++){
          TaskDetailItem t =  TaskDetailItem.fromJson(list[i]);
          tasks.add(t);
        }
        items.forEach((f){
          f.ifDownloadStr = '已下载';
          f.check = false;
        });
        return tasks;
      }else{
        Fluttertoast.showToast(msg: '未下载到数据!');
      }
    }catch(e){
      items.forEach((f){
        f.check = false;
      });
      Fluttertoast.showToast(msg: "error:"+e.toString());
      return null;
    }
    return null;
  }

  // 获取本地下载的盘点任务
  static Future<List<TaskDetailItem>> getTaskDetailList(String updateTime) async{
    DataBase dataBase = new DataBase();
    TaskModel itModel = await dataBase.getOneTaskByUpdateTime(updateTime);
    if(itModel!=null&&itModel.updateTime!=null&&itModel.jsonTxt!=null){
      String itsStr = itModel.jsonTxt;
      List<TaskDetailItem> list = new List();
      if(itsStr!='null'){
        var jsonList = json.decode(itsStr);
        for(int i=0;i<jsonList.length;i++){
          list.add(TaskDetailItem.fromJson(jsonList[i]));
        }
        return list;
      }
    }else{
      return null;
    }
  }

  static bool _checkDownLoad(List<TaskDetailItem> tasks, TaskItem item) {
    for(int i=0;i<tasks.length;i++){
      if(tasks[i].taskId == item.id)
        return true;
    }
    return false;
  }
}